Skip to content

fix (llamafile chat): uploading a tall, narrow image overflows a heap buffer in print_image() - #1093

Merged
aittalam merged 2 commits into
mainfrom
fix-image-issue
Dec 1, 2026
Merged

aittalam merged 2 commits into
mainfrom
fix-image-issue

Conversation

@aittalam

@aittalam aittalam commented Dec 1, 2026 •

Copy link
Copy Markdown
Member

Description

Fixes a heap buffer overflow in the image preview shown by /upload.

Root cause. print_image() scaled the uploaded image to the terminal with
32-bit arithmetic and no cap on height (image.cpp line 239):

  int xn = MIN(max_width, ws.ws_col);
  int yn = (height * xn) / width;
  yn = (yn + 1) & -2;
  unsigned char *resized = new unsigned char[xn * yn * 3];   // int-typed

A valid PNG 1 pixel wide and 223,697 pixels tall — under a kilobyte compressed —
gives 80 * 17,895,760 * 3 = 4,294,982,400, which wraps to 15,104, and
stbir_resize_uint8_srgb() then writes the full 4.29 GB past that buffer. The
crash lands in stbir__encode_uint8_srgb(). In combined mode the preview runs in
the server's process, so the built-in server goes down with the chat session.

Fix. The scaled destination is now bounded, and the arithmetic is not:

  • kImageMaxRows = 200 caps the preview at 200 lines of terminal; all dimension
    math is int64_t (new image_scaled_dims()), and the allocation is computed
    in size_t.
  • A height that hits the cap drags the width down with it, so previews of tall
    screenshots keep their aspect ratio instead of being squashed into a stripe.
  • Images past a 200:1 aspect ratio are refused rather than drawn, and
    print_image() returns -1. Refusal is the preview only: on_upload() notes
    that nothing was drawn and the original bytes still go to the model, so
    legitimate tall screenshots keep working.
  • stbir_resize_uint8_srgb()'s return value is checked. It was ignored, so a
    failed resize meant printing uninitialized memory.
  • ws.ws_col is clamped to at least 1. A terminal reporting 0 columns used to
    produce a zero-width allocation and an empty preview.
  • Very wide images are drawn instead of silently skipped. An image wider
    than about 80:1 scaled to a height of 0 and drew nothing; the height is
    now floored at two image rows, so it gets one line of text.

Tests. tests/print_image_test.cpp (registered in o/$(MODE)/tests) makes
1,791 assertions that the destination handed to the resize library stays within
max_width × 2 × kImageMaxRows × 3 across extreme widths and heights — including
the reported 1 × 223,697, 1 × 2²⁴, 1 × 2²⁸ — over terminal widths {0, 1, 10,
40, 80, 200} and width caps {1, 2, 8, 80, 1000}, and that ordinary images
(1920×1080 → 80×46, 1080×2400 → 80×178, …) draw exactly what they drew before.
No binary fixtures: the test synthesizes PNGs in memory with deflate uncompressed
blocks, and drives is_image() and print_image() on the reported dimensions.

Verified separately under AddressSanitizer against the production logic with the
reported bytes: refused, nothing allocated, no report; the same bytes through the
pre-fix formula crash in stbir__encode_uint8_srgb().

  .cosmocc/4.0.2/bin/make o//tests/print_image_test.runs   # 1791 PASSED
  .cosmocc/4.0.2/bin/make check                             # all pass

Severity, as we assess it: CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H
(5.5) — linear forward overflow, ~4.3 GB from the end of a 15 KB buffer, no
remote path (the web UI never calls print_image()), and the attacker must
supply the image.

Reported privately; there is no public issue for it yet.

Credit: Aman Verma (WSU), Swarn Priya (WSU), Peng Gao (VT) and Basavesh Ammanaghatta Shivakumar (WSU) 🙏

PR Type

  • 🐛 Bug Fix

Checklist

  • I understand the code I am submitting.
  • I have run this code locally and verified the change.
  • New and existing tests pass locally, or I have explained why tests were not run.
  • I have read and followed the contribution guidelines.
  • AI Usage:
    • No AI was used.
    • AI was used in an assistive capacity.
    • This PR includes substantial AI-generated content.

AI Usage Information

  • AI Model used: Qwen3.8 Flash Next
  • AI Developer Tool used: Pi

@aittalam
aittalam marked this pull request as ready for review December 1, 2026 15:40
@aittalam

aittalam commented Dec 1, 2026

Copy link
Copy Markdown
Member Author

Code review

No issues found. Checked for bugs and CLAUDE.md compliance.

Reviewed at bcdcb1d.

  • The fix closes the overflow. image_scaled_dims() does its math in 64-bit and keeps the width within the column cap and the height even and at most kImageMaxRows * 2. At 80 columns the largest destination is 96,000 bytes, and the half-block loop stays inside it.
  • The reported image is refused. 1×223,697 at 80 columns scales to a width of 0, so print_image() frees the decoded image and returns -1 before allocating anything.
  • Early returns don't leak, and on_upload(), the only caller of print_image(), handles the new -1.
  • The test expectations match the code. I built the test out of tree with the flags the Makefile uses and it reports 1,778 passed. On main, the same probe writes 16.8 MB to the terminal for a 10×1500 image; on this branch it writes 15 KB.

Three minor notes, none blocking:

  1. The header comment in the test says the last test uses PNM images, but it synthesizes PNGs (PNM is compiled out of our stb build).

    // The dimension math is tested directly, which needs no image files; the last
    // test drives print_image() itself on PNM images synthesized in memory.

  2. The on_upload() message blames the aspect ratio for any negative return, but print_image() also returns -1 when the resize or the final write() fails. Drawing a 320×240 image to a read-only fd returns -1 and would print "too tall or narrow". A decode failure can't reach this, since is_image() has already decoded the image.

    // ratio is too extreme to fit the terminal.
    if (print_image(1, content, 80) < 0)
    err("%s: image not drawn (too tall or narrow for this terminal),"
    " it will still be sent to the model",
    path);
    convert_image_to_uri(&markdown, content);

  3. Very wide images change behaviour, and the description doesn't mention it. An image wider than about 80:1 used to scale to a height of 0 and draw nothing (1000×10 writes 0 bytes on main). The floor of two image rows now gives it one line of text (2,805 bytes here). That seems like the better behaviour, but no test pins it.

    x = MIN(MAX(x, 1), (int64_t)max_width);
    y = MIN(MAX(y, 2), ycap);
    *xn = (int)x;

A follow-up commit on this branch addresses all three.

🤖 Generated with Claude Code

- on_upload() no longer blames the aspect ratio for every failed
  preview. print_image() also returns -1 when the resize or the write
  fails, so the message now says no preview was drawn and offers the
  aspect ratio as the likely cause.
- Document that image_scaled_dims() floors the height at two image
  rows, so an image too wide to fill one line of text is drawn as one
  line instead of scaling to nothing, and pin it with a test. On main
  such an image (wider than about 80:1 at 80 columns) drew nothing.
- The test header said PNM; the test synthesizes PNGs.

print_image_test now makes 1,791 assertions.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@aittalam
aittalam merged commit 3c6f7c5 into main Dec 1, 2026
2 checks passed
@aittalam
aittalam deleted the fix-image-issue branch December 1, 2026 15:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant